//
//  UserLocationManger.m
//  BuxProject
//
//  Created by iOS的 on 2021/12/1.
//  Copyright © 2020 Moitnea. All rights reserved.
//

#import "UserLocationManger.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "MainPublickTools.h"

@interface UserLocationManger ()<CLLocationManagerDelegate>
/*
 定位
 */
@property (strong, nonatomic) CLLocationManager* managerloca; //
//是否有定位权限
@property (nonatomic,assign) BOOL isOpenLoaction;

@end

@implementation UserLocationManger
+ (instancetype)shareLocationManager {
    static UserLocationManger *sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedAccountManagerInstance = [[self alloc] init];
    });
    return sharedAccountManagerInstance;
}

//获取定位信息
-(void)getMylocationInfo{
    //初始化定位管理类
    self.managerloca = [[CLLocationManager alloc] init];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [self.managerloca requestWhenInUseAuthorization];
    }
    //delegate
    self.managerloca.delegate = self;
    //The desired location accuracy.//精确度
    self.managerloca.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    //Specifies the minimum update distance in meters.
    //距离
    self.managerloca.distanceFilter = 10;
   
    //开始定位
    [self.managerloca startUpdatingLocation];
}
-(void)toastPopView{
    if (self.commaLocationsTipBlock) {
        self.commaLocationsTipBlock(NO);
        return;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"定位服务不可用" message:@"请到“设置->隐私->定位服务”中开启定位" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }]];
    [[MainPublickTools obtaincurrentController] presentViewController:alert animated:YES completion:nil];
    
    NSError *error = nil;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"location" object:error];
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    [self.managerloca stopUpdatingLocation];
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    if (locations.count > 0) {
        CLLocation *newLocation = [locations lastObject];
        NSLog(@"%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
        [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            for (CLPlacemark * placemark in placemarks) {
                NSMutableDictionary *locationDic = [placemark addressDictionary].mutableCopy;
                [locationDic setObject:[NSString stringWithFormat:@"%f",newLocation.coordinate.latitude] forKey:@"lat"];
                [locationDic setObject:[NSString stringWithFormat:@"%f",newLocation.coordinate.longitude] forKey:@"long"];
                if (locationDic) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"location" object:locationDic userInfo:@{@"CLLocation":newLocation}];
                    if (self.commaLocationsFinishBlock) {
                        self.commaLocationsFinishBlock(locationDic);
                    }
                }
            }
        }];
    }
    
}
/** 定位服务状态改变时调用*/
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusDenied) {
        // 类方法，判断是否开启定位服务
        if ([CLLocationManager locationServicesEnabled]) {
            [self toastPopView];
            NSLog(@"定位服务开启，被拒绝");
        } else {
            [self toastPopView];
            NSLog(@"定位服务关闭，不可用");
        }
        self.isOpenLoaction = NO;
    }
    else if (status == kCLAuthorizationStatusNotDetermined)
    {
        //下次询问
        self.isOpenLoaction = NO;
    }
    else if (status == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        if (!self.isOpenLoaction) {
            if (self.commaLocationsTipBlock) {
                self.commaLocationsTipBlock(YES);
                self.isOpenLoaction = YES;
            }
            
        }
        
    }
}


@end
